package com.bfg.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MailServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out=resp.getWriter();
		resp.setContentType("text/html");
		try {
			Properties props=new Properties();
			props.put("mail.smtps.host", "smtp.gmail.com");
			props.put("mail.smtps.auth", "true");
			props.put("mail.debug", "true");
			props.put("mail.smtps.port", "465");
			props.put("mail.smtps.socketFactory.port", "465");
			props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtps.socketFactory.fallback", "false");
			Session session = Session.getDefaultInstance(props,
					new javax.mail.Authenticator() {

					protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("xkjRZx.da.str8.edge@gmail.com", "myx61gubrak");
					}
					});
			String strSender=req.getParameter("txtSender");
			String strReceiver=req.getParameter("txtReceiver");
			String strSubject=req.getParameter("txtSubject");
			String strMessage=req.getParameter("txtMessage");
			
			Message message=new MimeMessage(session);
			message.setFrom(new InternetAddress(strSender));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strReceiver,false));
			message.setSubject(strSubject);
			message.setContent(strMessage,"text/plain");
			Transport transport=session.getTransport("smtps");
			transport.connect("smtp.gmail.com", "xkjRZx.da.str8.edge@gmail.com", "myx61gubrak");
			transport.sendMessage(message, message.getAllRecipients());
			out.println("Email has been sent.");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			out.println("ERROR");
		}
	}
}
